package org.jeecg.modules.zcgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgBaseController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.zcgl.entity.*;
import org.jeecg.modules.zcgl.enums.PayStatusEnum;
import org.jeecg.modules.zcgl.enums.PaymentStatusEnum;
import org.jeecg.modules.zcgl.service.ICustomerInfoService;
import org.jeecg.modules.zcgl.service.ILeaseContractInfoService;
import org.jeecg.modules.zcgl.service.IPayablesDetailsService;
import org.jeecg.modules.zcgl.service.IPayablesInfoService;
import org.jeecg.modules.zcgl.util.NoUtils;
import org.jeecg.modules.zcgl.vo.PayablesInfoPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 应付款项
 * @Author: jeecg-boot
 * @Date: 2020-06-30
 * @Version: V1.0
 */
@Api(tags = "应付款项")
@RestController
@RequestMapping("/zcgl/payablesInfo")
@Slf4j
public class PayablesInfoController extends JeecgBaseController<PayablesInfoPage, PayablesInfo, IPayablesInfoService> {
    @Autowired
    private IPayablesInfoService payablesInfoService;
    @Autowired
    private IPayablesDetailsService payablesDetailsService;
    @Autowired
    private ILeaseContractInfoService leaseContractInfoService;
    @Autowired
    private ICustomerInfoService customerInfoService;

    /**
     * 分页列表查询
     *
     * @param payablesInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "应付款项-分页列表查询")
    @ApiOperation(value = "应付款项-分页列表查询", notes = "应付款项-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(PayablesInfo payablesInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Map<String, String[]> parameterMap = new HashMap(req.getParameterMap());
        parameterMap.remove("managerId");
        parameterMap.remove("regional");
        QueryWrapper<PayablesInfo> queryWrapper = QueryGenerator.initQueryWrapper(payablesInfo, req.getParameterMap());

        if (StringUtils.isNotBlank(req.getParameter("managerId"))) {
            queryWrapper.lambda().inSql(PayablesInfo::getAssetId, "SELECT asset.id FROM zcgl_asset_info AS asset WHERE asset.manager_id = '" + req.getParameter("managerId") + "'");
        }
        if(StringUtils.isNotBlank(req.getParameter("regional"))){
            queryWrapper.lambda().inSql(PayablesInfo::getAssetId, "SELECT asset.id FROM zcgl_asset_info AS asset WHERE asset.regional = '" + req.getParameter("regional") + "'");
        }

        Page<PayablesInfo> page = new Page<PayablesInfo>(pageNo, pageSize);
        IPage<PayablesInfo> pageList = payablesInfoService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param payablesInfoPage
     * @return
     */
    @AutoLog(value = "应付款项-添加")
    @ApiOperation(value = "应付款项-添加", notes = "应付款项-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody PayablesInfoPage payablesInfoPage) {
        String message = this.checkModel(payablesInfoPage);
        if (message != null) {
            return Result.error(message);
        }
        PayablesInfo payablesInfo = new PayablesInfo();
        BeanUtils.copyProperties(payablesInfoPage, payablesInfo);
        payablesInfo.setPayablesNo(NoUtils.getPayablesNo());
        payablesInfoService.saveMain(payablesInfo, payablesInfoPage.getPayablesDetailsList());
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param payablesInfoPage
     * @return
     */
    @AutoLog(value = "应付款项-编辑")
    @ApiOperation(value = "应付款项-编辑", notes = "应付款项-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody PayablesInfoPage payablesInfoPage) {
        String message = this.checkModel(payablesInfoPage);
        if (message != null) {
            return Result.error(message);
        }
        PayablesInfo payablesInfo = payablesInfoService.getById(payablesInfoPage.getId());
        if (payablesInfo == null) {
            return Result.error("未找到对应数据");
        }
        BeanUtils.copyProperties(payablesInfoPage, payablesInfo);
        payablesInfoService.updateMain(payablesInfo, payablesInfoPage.getPayablesDetailsList());
        return Result.ok("编辑成功!");
    }

    private String checkModel(PayablesInfo payablesInfo) {
        if (StringUtils.isNotBlank(payablesInfo.getLeaseContractId())) {
            LeaseContractInfo leaseContractInfo = leaseContractInfoService.getById(payablesInfo.getLeaseContractId());
            if (leaseContractInfo != null) {
                payablesInfo.setAssetId(leaseContractInfo.getAssetId());
                payablesInfo.setAssetSubIds(leaseContractInfo.getAssetSubIds());
                payablesInfo.setCustomerId(leaseContractInfo.getCustomerId());
            } else {
                return "合同信息不存在";
            }
        } else {
            if (StringUtils.isBlank(payablesInfo.getCustomerId())) {
                return "请填写客户信息";
            }
            CustomerInfo customerInfo = customerInfoService.getById(payablesInfo.getCustomerId());
            if (customerInfo == null) {
                return "客户信息不存在";
            }
        }
        if (payablesInfo.getPayStatus() == null) {
            payablesInfo.setPayStatus(PayStatusEnum.UNPAID.getStatus());
        }
        return null;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "应付款项-通过id删除")
    @ApiOperation(value = "应付款项-通过id删除", notes = "应付款项-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        payablesInfoService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "应付款项-批量删除")
    @ApiOperation(value = "应付款项-批量删除", notes = "应付款项-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.payablesInfoService.delBatchMain(Arrays.asList(ids.split(CommonConstant.DEFAULT_SEPARATOR)));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "应付款项-通过id查询")
    @ApiOperation(value = "应付款项-通过id查询", notes = "应付款项-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        PayablesInfo payablesInfo = payablesInfoService.getById(id);
        if (payablesInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(payablesInfo);

    }

    @AutoLog(value = "应付款项-付款")
    @ApiOperation(value = "应付款项-付款", notes = "应付款项-付款")
    @PostMapping(value = "/payment")
    public Result<?> payment(PayablesInfo vo) {
        if (vo.getPaymentType() == null) {
            return Result.error("请选择付款方式");
        }
        if (vo.getPaymentDate() == null) {
            return Result.error("请选择付款日期");
        }
        if (StringUtils.isBlank(vo.getPayeeBy())) {
            return Result.error("请选择收款人");
        }
        PayablesInfo payablesInfo = payablesInfoService.getById(vo.getId());
        if (payablesInfo == null) {
            return Result.error("应付款项不存在");
        }
        payablesInfo.setPayeeBy(vo.getPayeeBy());
        payablesInfo.setPayStatus(PaymentStatusEnum.PAID.getStatus());
        payablesInfo.setPaymentDate(vo.getPaymentDate());
        payablesInfo.setPaymentType(vo.getPaymentType());
        payablesInfo.setPaymentRemark(vo.getPaymentRemark());

        if (StringUtils.isBlank(vo.getPaymentBy())) {
            LoginUser sysUser = JwtUtil.getLoginUser();
            vo.setPaymentBy(sysUser.getId());
        }
        payablesInfo.setPaymentBy(vo.getPaymentBy());
        payablesInfoService.updateById(payablesInfo);
        return Result.ok("操作成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "应付款项详情通过主表ID查询")
    @ApiOperation(value = "应付款项详情主表ID查询", notes = "应付款项详情-通主表ID查询")
    @GetMapping(value = "/queryPayablesDetailsByMainId")
    public Result<?> queryPayablesDetailsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<PayablesDetails> payablesDetailsList = payablesDetailsService.selectByMainId(id);
        return Result.ok(payablesDetailsList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param payablesInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PayablesInfo payablesInfo) {
        return super.exportXls(request, payablesInfo, PayablesInfoPage.class, "应付款项");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PayablesInfoPage.class);
    }

    @Override
    public List<PayablesInfoPage> exportList(List<PayablesInfo> list) {
        List<PayablesInfoPage> pageList = new ArrayList<PayablesInfoPage>();
        if (list != null) {
            for (PayablesInfo main : list) {
                PayablesInfoPage vo = new PayablesInfoPage();
                BeanUtils.copyProperties(main, vo);
                List<PayablesDetails> assetInfoSubList = payablesDetailsService.selectByMainId(main.getId());
                vo.setPayablesDetailsList(assetInfoSubList);
                pageList.add(vo);
            }
        }
        return pageList;
    }


    @Override
    public boolean importSave(PayablesInfoPage vo) {
        PayablesInfo po = new PayablesInfo();
        BeanUtils.copyProperties(vo, po);
        String checkStr = this.checkModel(po);
        if (checkStr != null) {
            throw new JeecgBootException(checkStr);
        }
        po.setPayablesNo(NoUtils.getPayablesNo());
        payablesInfoService.saveMain(po, vo.getPayablesDetailsList());
        return true;
    }

}
